package com.lsh.consumer;

import com.lsh.util.FtpFileUtils;
import com.lsh.util.GetIPPortUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Set;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/8/7 9:17 上午
 * @desc ：RabbitMQ消费者
 */
//@Component
@Slf4j
public class RabbitMQConsumer {


    @RabbitHandler
    @RabbitListener(queues = "hw_data") //指定监听哪个队列的消息
    public void receiveMsg(Message msg) {
        try {
            log.info("===========start===========");
            //获得ip地址
            Set<String> inetAddresses = GetIPPortUtil.getInetAddresses();
            String ip;
//            for (String inetAddress : inetAddresses) {
//                ip = inetAddress;
//            }
            ip = "192.168.103.10";
            //获得端口号
            String tomcatPort = GetIPPortUtil.getPortByMBean();
            //写入文件
            byte[] body = msg.getBody();
            String today = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now());
            String hours = DateTimeFormatter.ofPattern("HH").format(LocalDateTime.now());
            //判断路径是否存在，如果不存在，则创建文件
//            File file = new File("/data/dataWarehouseOss/"+ip+"/"+tomcatPort+"/"+today);
            File file = new File("/data/hw_data/");
            if (!file.exists()) {
                log.info("不存在该路径，开始创建...");
                file.mkdirs();
                log.info("路径创建完成...");
            }
             file = new File("/data/hw_data/"+today+"_"+hours+"_"+ip+"_"+tomcatPort+".txt");
            if (!file.exists()) {
                log.info("不存在当天文件，开始创建...");
                file.createNewFile();
                log.info("文件创建完成...");
            }
            //创建一个输出流
            FileOutputStream fos = new FileOutputStream(file,true);
            //创建文件
            //写入字节数组
            fos.write(body);
            fos.close();
            boolean connect = FtpFileUtils.connect("/", "192.168.19.13", 21, "pengxiaoyang", "pxy19840208");
            log.info("ftp是否连接成功："+connect);
            String path = "/lshrabbitMQ/"+"hw_data/";
            log.info("path:"+path);
            FtpFileUtils.upload(file,path);
            System.out.println(msg);
            log.info("===========end===========");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
